<?php

namespace App\Imports;

use App\Http\Util\Tool;
use App\Models\Question;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;

class QuestionImport implements ToCollection
{

    public $cid;
    public $lid;

    public function __construct($data)
    {
        $this->cid = $data['cid'];
        $this->lid = $data['lid'];
    }

    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function collection(Collection $rows)
    {
        try{
            // TODO: Implement collection() method.
            //解析excel中的数据
            $data=json_decode(json_encode($rows),true);
            //去掉第一行的标题
            array_splice($data, 0, 1);
            $log = '';
            //拼接字段入库
            foreach ($data as $row)
            {
                switch ($row[0]){
                    case "判断题":
                        $row[0] = 'judge';
                        $row[4] = '';
                        $row[5] = '';
                        break;
                    case "多选题":
                        $row[0] = 'choose';
                        break;
                    default:
                        $row[0] = 'one_choose';
                        break;
                }
                $query['cate_id']=$this->cid??0;
                $query['level']=$this->lid??0;
                $query['type']=$row[0]??'';
                $query['stem']=$row[1]??'';
                $query['answer']=$row[2]??'';
                $query['options']=$row[3]??0;
                $query['a']=$row[4]??'';
                $query['b']=$row[5]??'';
                $query['c']=$row[6]??'';
                $query['d']=$row[7]??'';
                $query['e']=$row[8]??'';
                $query['score'] = $row[9];
                if(!$result=Question::create($query)){
//                    Tool::logInfo('数据导入失败', json_encode($query), $file = 'lumen');
                }
            }
        }catch (\Exception $e){
            echo $e->getMessage();
//                    Tool::logError('数据导入失败',$e->getMessage(), $file = 'lumen');
        }
    }


    public function createData($rows)
    {
        //todo
    }
}
